package cn.tedu._04mvcboot03.exception;

import cn.tedu._04mvcboot03.common.response.JsonResult;
import cn.tedu._04mvcboot03.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String message = ex.getFieldError().getDefaultMessage();
        log.error("message = " + message);

        //{"code":10500,"msg":"参数校验失败","data":"Validation校验注解中的message参数的值"}
        return new JsonResult(StatusCode.VALIDATED_ERROR, message);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String message = ex.getMessage();
        log.error("message = " + message);

        return new JsonResult(StatusCode.VALIDATED_ERROR, message);
    }

    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException ex){
        String message = ex.getMessage();
        log.error("message = " + message);

        return new JsonResult(StatusCode.VALIDATED_ERROR, message);
    }

    @ExceptionHandler
    public JsonResult doHandleThrowableException(Throwable ex){
        String message = ex.getMessage();
        log.error("message = " + message);

        return new JsonResult(StatusCode.THROWABLE_ERROR, message);
    }

}








